package models

import (
	"bytes"
	"crypto/md5"
	"encoding/hex"
	"strconv"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

// 订单日志表
type TLogOrder struct {
	OrderId    string    `orm:"pk;size(50);column(orderId)"`
	Uin        uint      `orm:"index"`
	CreateTime time.Time `orm:"auto_now_add;type(datetime);index"`
	DealTime   time.Time `orm:"auto_now;type(datetime)"`
	Money      uint      `orm:"default(0)"`
	Channel    string    `orm:"size(16);column(channel)"`
	Status     uint16    `orm:"default(0)"`
	RechargeId uint      `orm:"default(0);column(rechargeId)"`
}

// 兑换物品表
type TRechargeItem struct {
	Id    uint   `json:"id";orm:"pk"`
	Name  string `json:"name";orm:"size(16);default()"`
	Money uint   `json:"money";orm:"default(0)"`
	Count uint   `json:"count";orm:"default(0)"`
}

// 兑换物品表--苹果
type TRechargeItemIos struct {
	Id    uint   `json:"id";orm:"pk"`
	Name  string `json:"name";orm:"size(16);default()"`
	Money uint   `json:"money";orm:"default(0)"`
	Count uint   `json:"count";orm:"default(0)"`
}

// 房间玩家胜局预设日志表
type TLogRoomSet struct {
	Id         uint64    `orm:"pk;auto"`
	Uin        uint      `orm:"index"`
	Agent      uint      `orm:"index"`
	Round      uint      `orm:"default(0);column(round)"`
	SubPoker   uint      `orm:"column(subPoker);default(0)"`
	MPoker     bool      `orm:"column(mPoker)"`
	GPoker     bool      `orm:"column(gPoker)"`
	Multiple   uint      `orm:"column(multiple)"`
	Person     uint      `orm:"default(0)"`
	PayAll     bool      `orm:"column(payAll)"`
	PlayerInfo string    `orm:"column(playerInfo);size(100)"`
	Status     uint16    `orm:"default(0)"`
	Oid        string    `orm:"size(35);index"`
	CreateTime time.Time `orm:"auto_now_add;type(datetime)"`
	UpdateTime time.Time `orm:"auto_now;type(datetime)"`
}

// 设置引擎为 INNODB
func (u *TLogOrder) TableEngine() string {
	return "INNODB"
}

func (u *TRechargeItem) TableEngine() string {
	return "INNODB"
}

func (u *TRechargeItemIos) TableEngine() string {
	return "INNODB"
}

func (u *TLogRoomSet) TableEngine() string {
	return "INNODB"
}

// 设置表名
func (u *TLogOrder) TableName() string {
	return "tLogOrder"
}

func (u *TRechargeItem) TableName() string {
	return "tRechargeItem"
}

func (u *TRechargeItemIos) TableName() string {
	return "tRechargeItemIos"
}

func (u *TLogRoomSet) TableName() string {
	return "tLogRoomSet"
}

// 充值信息
type Recharge struct {
	UserId     int
	RechargeID int
	Channel    string
}

// 充值返回信息
type Pay struct {
	Name    string `json:"name"`
	OrderId string `json:"orderId"`
	Money   int    `json:"money"`
}

// 返回充值列表
type ItemList struct {
	Id    uint   `json:"id"`
	Name  string `json:"name"`
	Money uint   `json:"money"`
}

// 获取充值列表
type PItem struct {
	Channel string
}

// 回调信息
type CheckInfo struct {
	Code    string
	Id      string
	Order   string
	Cporder string
	Info    info
	Amount  string
	App_id  string
}

type info struct {
	Buy_number int
}

// 平台获取用户信息
type PlayerInfo struct {
	Code   int    `json:"code"`
	GameId uint   `json:"gameId"`
	Name   string `json:"name"`
}

// 平台获取用户信息
type RoomInfo struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

// 发送房卡
type SendCard struct {
	GameId  int    `json:"gameId"`
	Channel string `json:"channel"`
	CardNum int    `json:"cardNum"`
}

// 消息状态
type MsgInfo struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

// 房间胜局设置
type Room struct {
	Agent      int32     `json:"agent"`
	UserId     int32     `json:"userId"`
	Person     int32     `json:"person"`
	Round      int32     `json:"round"`
	Poker      int32     `json:"poker"`
	PayAll     bool      `json:"payAll"`
	Power      []Player  `json:"power"`
	MPoker     bool      `json:"mPoker"`
	GPoker     bool      `json:"gPoker"`
	Multiple   int32     `json:"multiple"`
	Oid        string    `json:"oid"`
	CreateTime time.Time `json:"createTime"`
	Status     int32     `json:"status"`
}

// 胜局玩家
type Player struct {
	GameUserId int32  `json:"gameUserId"`
	GameName   string `json:"gameName"`
	GoodCard   int32  `json:"goodCard"`
}

// 获取胜场设置列表
type RoomList struct {
	UserId   uint `json:"userId"`
	Agent    uint `json:"agent"`
	Page     int  `json:"page"`
	PageSize int  `json:"pageSize"`
}

type RoomData struct {
	Code int    `json:"code"`
	Data []Room `json:"data"`
	Ct   int64  `json:"ct"`
}

func init() {
	//orm.RegisterDriver("mysql", orm.DRMySQL)
	//
	//orm.RegisterDataBase("default", "mysql", "root:root@tcp/poker?charset=utf8&loc=Asia%2FShanghai")
	//
	//orm.RegisterModel(new(TAccount),new(TLogLogin),new(TLogPlay),new(TLogOrder),new(TRechargeItem))
}

// 创建订单号
func CreateOrder(recharge Recharge) (string, time.Time) {
	t := time.Now()
	beego.Info(" date = ", t)

	var buffer bytes.Buffer
	buffer.WriteString(strconv.Itoa(recharge.UserId))
	buffer.WriteString("quwan")
	buffer.WriteString(strconv.Itoa(recharge.RechargeID))
	buffer.WriteString(strconv.FormatInt(t.UnixNano(), 10))
	s := buffer.String()
	beego.Info("str = ", s)

	md5Ctx := md5.New()
	//io.WriteString(md5Ctx, s)
	md5Ctx.Write([]byte(s))
	cipherStr := hex.EncodeToString(md5Ctx.Sum(nil))
	beego.Info("md5 = ", cipherStr)

	return cipherStr, t
}

// 记录订单
func PayInfo(order TLogOrder) error {
	o := orm.NewOrm()
	id, err := o.Insert(&order)
	if err != nil {
		beego.Debug("error ", err)
		return err
	}
	beego.Debug("id ", id)
	return nil
}

// 获取玩家信息
func GetUserInfo(id uint) TAccount {
	o := orm.NewOrm()

	item := TAccount{Uin: id}

	err := o.Read(&item)
	if err != nil {
		beego.Error("get user err = ", err)
		return TAccount{}
	}

	return item
}

// 获取商品金额
func GetItem(id int) TRechargeItem {
	o := orm.NewOrm()

	item := TRechargeItem{Id: uint(id)}

	o.Read(&item)

	return item
}

// 获取商品金额--苹果
func GetItemI(id int) TRechargeItemIos {
	o := orm.NewOrm()

	item := TRechargeItemIos{Id: uint(id)}

	o.Read(&item)

	return item
}

// 获取商品列表
func GetItemAndroid() []*TRechargeItem {
	o := orm.NewOrm()

	var items []*TRechargeItem
	user := new(TRechargeItem)
	o.QueryTable(user).All(&items)
	beego.Info("item = ", items)
	return items
}

// 获取商品列表--苹果
func GetItemIos() []*TRechargeItemIos {
	o := orm.NewOrm()

	var items []*TRechargeItemIos
	user := new(TRechargeItemIos)
	o.QueryTable(user).All(&items)
	beego.Info("item IOS = ", items)
	return items
}

// 更新玩家房卡
func UpdateCards(uin, card uint) uint {
	o := orm.NewOrm()

	account := TAccount{Uin: uin}
	o.Read(&account)

	account.Cards += card
	_, err := o.Update(&account, "Cards")
	if err != nil {
		beego.Info("err = ", err)
		return 0
	} else {
		//o.Read(&account)
		return account.UserId
	}
}

// 查询订单更新状态
func CheckOrder(orderId string, money uint) TLogOrder {
	o := orm.NewOrm()

	order := TLogOrder{OrderId: orderId}

	err := o.Read(&order)

	if err == orm.ErrNoRows {
		beego.Info("查询不到")
	} else if err == orm.ErrMissPK {
		beego.Info("找不到主键")
	} else {
		if order.Status == 0 {
			if money == 0 || (money != 0 && money == order.Money) {
				order.Status = 1
				if _, err := o.Update(&order, "Status"); err == nil {
					beego.Info("更新成功")
					return order
				} else {
					beego.Info("更新失败")
				}
			} else {
				beego.Info("金额错误")
			}
		} else {
			beego.Info("已支付成功")
		}
	}

	return TLogOrder{}
}
